package com.example.demo.common.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.text.NumberFormat;

/**
 * 源数据金额单位: 元
 * 支持类型: ? extends Number
 *
 *         0 --> 0.00
 * 100000000 --> 1,000,000.00
 * 123456789 --> 1,234,567.89
 *
 * PS:
 * ✅ #,##0.00
 * ❌ #,###.##
 *
 * @author Shanks
 * @date 2020-11-07
 */
public class YuanCurrencyNoPrefixSerializer extends JsonSerializer<Number> {

    @Override
    public void serialize(Number number, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        NumberFormat numberFormat = NumberFormat.getCurrencyInstance();
        // 设置小数部分所允许的最少位数(不足则后面补0)
        numberFormat.setMinimumFractionDigits(2);
        // 设置小数部分所允许的最多位数(超过则四舍五入)
        numberFormat.setMaximumFractionDigits(3);
        String format = numberFormat.format(number);
        String substring = format.substring(1);
        jsonGenerator.writeString(substring);
    }
}